package org.ainlolcat.ainscience;

import org.ainlolcat.ainscience.entity.Entity;
import org.ainlolcat.ainscience.entity.links.EqualLink;
import org.ainlolcat.ainscience.entity.links.Link;
import org.ainlolcat.ainscience.entity.links.NearestLink;
import org.ainlolcat.ctp.util.IDGenerator;
import org.jdom.Element;

import java.awt.*;
import java.text.DecimalFormatSymbols;
import java.util.*;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ain
 * Date: 10/25/11
 * Time: 12:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class tools {
    private static char chDec = new DecimalFormatSymbols().getDecimalSeparator();

    public static Double parseDouble(Object obj){
        if (obj instanceof Double)
            return (Double) obj;

        String str = obj.toString();
        /*if(chDec == ','){
            str = str.replace('.', chDec);
        }
        if(chDec == '.'){
            str = str.replace(',', chDec);
        } */
        str = str.replace(',', '.');
        return Double.parseDouble(str);
    }

    public static Integer parseInteger(String str){
        return Integer.parseInt(str);
    }

    public static Boolean parseBoolean(String str){
        return Boolean.parseBoolean(str);
    }

    public static Dimension getScreenSize(){
        return java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    }

    public static Integer generateID(){
        return IDGenerator.getNextIntegerID();
    }

    public static Map<String, Link> parseLinks(List<Element> elinks, Entity entity){
        Map<String, Link> links = new HashMap<String, Link>();
        for (Element elink : elinks){
            Link link = prepareLink(elink);
            link.setEntity(entity);
            links.put(link.getName(), link);
        }
        return links;
    }

    //TODO remove hardcode
    private static Link prepareLink(Element elink){
        String type = elink.getAttributeValue("type");
        if ("equal".equals(type)){
            return new EqualLink(elink.getAttributeValue("name"),
                    tools.parseInteger(elink.getAttributeValue("column")),
                    elink.getAttributeValue("l2entity"),
                    tools.parseInteger(elink.getAttributeValue("l2column")),
                    elink.getAttributeValue("type")
            );
        }
        if ("nearest".equals(type)){
            return new NearestLink(elink.getAttributeValue("name"),
                    tools.parseInteger(elink.getAttributeValue("column")),
                    elink.getAttributeValue("l2entity"),
                    tools.parseInteger(elink.getAttributeValue("l2column")),
                    elink.getAttributeValue("type")
            );
        }
        throw new IllegalArgumentException("Unknown link type: " + type);
    }
}
